<template>

  <div class="app-container">


    <!--第一行-->
    <el-row :gutter="20">
      <!--栅格布局4分-->
      <el-col :span="4">
        <!--咨询分类卡片 -->
        <el-card class="box-card" style="margin-top: 77px;">

          <el-tree :data="channelDateList"
                   :props="defaultProps"
                   accordion
                   @node-click="handleNodeClick">
          </el-tree>


        </el-card>
        <!--咨询分类卡片 -->
      </el-col>
      <!--栅格布局4分--->

      <!--栅格布局20分-->
      <el-col :span="20">
        <!--内联表单-->
        <el-form :inline="true" style="padding-top: 15px;">
          <el-form-item>
            <el-input
              style="width: 350px;"
              v-model="pagination.queryParams.queryString"
              placeholder="咨询名/咨询作者名/咨询摘要"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button size="medium" icon="el-icon-search" @click="handleCurrentChange(1)">搜索</el-button>
          </el-form-item>

        </el-form>
        <!--内联表单-->

        <!--字典表格卡片-->
        <el-card class="box-card">
          <!-- 按钮处理面板 -->
          <div class="btn-panel" style="margin-bottom: 10px;">
            <el-button size="mini" type="primary" icon="el-icon-plus" @click="handleAddDialog" >新 增</el-button>
            <el-button  size="mini" type="warning" icon="el-icon-edit" @click="handleUpdateDialog" >修 改</el-button>
            <el-button  size="mini" type="danger" icon="el-icon-delete" @click="handleDelete">删 除</el-button>
            <el-button size="mini" type="success" icon="el-icon-plus" @click="handleAddArticleAttachmentDialog" >添加附件</el-button>
          </div>
          <!-- 按钮处理面板 -->

          <!--展示表格-->
          <el-table
            height="600"
            ref="multipleTable"
            :data="dataList"
            tooltip-effect="dark"
            style="width: 100%"
            border
            stripe
            @selection-change="handleSelectionChange">

            <el-table-column
              type="selection"
              width="55">
            </el-table-column>

            <el-table-column
              label="咨询标题"
              prop="title">
            </el-table-column>

            <el-table-column
              label="咨询简要"
              prop="summary"
              width="500">
            </el-table-column>


            <el-table-column
              label="作者"
              prop="author">
            </el-table-column>


            <el-table-column
              prop="created"
              label="创建时间">
            </el-table-column>

            <el-table-column
              prop="sort"
              width="80"
              label="排序号">
            </el-table-column>

            <el-table-column
              prop="status"
              width="80"
              label="状态">
              <template slot-scope="scope">
                <el-tag size="small" v-if="scope.row.status === 0" type="danger">待激活</el-tag>
                <el-tag size="small" v-else-if="scope.row.status === 1" type="success">正常</el-tag>
              </template>
            </el-table-column>

          </el-table>
          <!--展示表格-->

          <!--分页组件-->
          <el-pagination
            :current-page="pagination.currentPage"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            layout="total,sizes, prev, pager, next, jumper">
          </el-pagination>
          <!--分页组件-->


        </el-card>
        <!--字典表格卡片-->

      </el-col>
      <!--栅格布局20分-->

    </el-row>
    <!--第一行-->


    <!--新增咨询对话框-->
    <el-dialog
      :close-on-click-modal="false"
      title="新增咨询对话框"
      :visible.sync="dialogFormVisible"
      width="1200px"
      :before-close="handleAddFormClose">

      <el-form :model="formData" :rules="rule" ref="dataAddForm">


        <el-form-item label="所属咨询栏目" prop="parentId">
          <el-select v-model="formData.channelId" placeholder="所属咨询栏目">
            <template v-for="item in channelDateList">
              <el-option :label="item.name" :value="item.id"></el-option>
              <template v-for="child in item.children">
                <el-option :label="child.name" :value="child.id">
                  <span>{{ "- " + child.name }}</span>
                </el-option>
              </template>
            </template>
          </el-select>
        </el-form-item>



        <el-form-item label="咨询标题" prop="title" label-width="100px">
          <el-input v-model="formData.title" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="咨询配图" prop="titleImg" label-width="100px">
          <el-upload
            action=""
            class="avatar-uploader"
            :http-request="handleHttpRequest"
            :show-file-list="false"
            :before-upload="beforeTitleImageUpload">
            <img style="width: 100%;height: 300px;" v-if="titleImg" :src="titleImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>



        <el-form-item label="咨询摘要"  prop="summary" label-width="100px">
          <el-input v-model="formData.summary" autocomplete="off"></el-input>
        </el-form-item>


        <el-form-item label="咨询作者"  prop="author" label-width="100px">
          <el-input v-model="formData.author" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="咨询内容" prop="content">
          <mavon-editor
            ref=md
            @imgAdd="handleEditorImgAdd"
            v-model="formData.content"/>
        </el-form-item>

        <el-form-item label="排序号"  prop="sort" label-width="100px">
          <el-input v-model="formData.sort" autocomplete="off"></el-input>
        </el-form-item>


        <el-form-item label="咨询附件"  label-width="100px">
          <el-upload
            action=""
            class="upload-demo"
            :before-upload="handleAttachmentBeforeUpload"
            :http-request="handleAttachmentHttpRequest"
            :show-file-list="true"
            :limit="1">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>


        <el-form-item label="状态"  prop="status" label-width="100px">
          <el-radio-group v-model="formData.status">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleAddFormClose()">取 消</el-button>
        <el-button type="primary" @click="handleAdd('dataAddForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!--新增咨询对话框-->


    <!--修改咨询对话框-->
    <el-dialog
      title="修改咨询对话框"
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible4Edit"
      width="1200px"
      :before-close="handleEditFormClose">

      <el-form :model="formData" :rules="rule" ref="dataEditForm">

        <el-form-item label="所属咨询栏目" prop="parentId">
          <el-select v-model="formData.channelId" placeholder="所属咨询栏目">
            <template v-for="item in channelDateList">
              <el-option :label="item.name" :value="item.id"></el-option>
              <template v-for="child in item.children">
                <el-option :label="child.name" :value="child.id">
                  <span>{{ "- " + child.name }}</span>
                </el-option>
              </template>`
            </template>
          </el-select>
        </el-form-item>



        <el-form-item label="咨询标题" prop="title" label-width="100px">
          <el-input v-model="formData.title" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="咨询配图" prop="titleImg" label-width="100px">
          <el-upload
            action=""
            class="avatar-uploader"
            :http-request="handleHttpRequest"
            :show-file-list="false"
            :before-upload="beforeTitleImageUpload">
            <img style="width: 100%;height: 300px;" v-if="titleImg" :src="titleImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>



        <el-form-item label="咨询摘要"  prop="summary" label-width="100px">
          <el-input v-model="formData.summary" autocomplete="off"></el-input>
        </el-form-item>


        <el-form-item label="咨询作者"  prop="author" label-width="100px">
          <el-input v-model="formData.author" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="咨询内容" prop="content">
          <mavon-editor ref = "md"  @imgAdd="handleEditorImgAdd"  v-model="formData.content"/>
        </el-form-item>

        <el-form-item label="排序号"  prop="sort" label-width="100px">
          <el-input v-model="formData.sort" autocomplete="off"></el-input>
        </el-form-item>


        <el-form-item label="状态"  prop="status" label-width="100px">
          <el-radio-group v-model="formData.status">
            <el-radio :label="0" >禁用</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleEditFormClose()">取 消</el-button>
        <el-button type="primary" @click="handleEdit('dataEditForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!--修改咨询对话框-->


    <!--添加咨询附件对话框-->
    <el-dialog
      title="添加咨询附件对话框"
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible4AddAttachment"
      width="1200px"
      :before-close="handleAddAttachmentFormClose">
      <el-form :model="articleAttachment"  ref="dataArticleAttachmentForm">
        <el-form-item label="咨询附件" label-width="100px">
          <el-upload
            action=""
            class="upload-demo"
            :before-upload="handleAttachmentBeforeUpload"
            :http-request="handleAttachmentHttpRequest"
            :show-file-list="true"
            :limit="1">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">可接受上传Excel以及Word</div>
          </el-upload>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleAddAttachmentFormClose()">取 消</el-button>
        <el-button type="primary" @click="handleAddArticleAttachment('dataArticleAttachmentForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!--添加咨询附件对话框-->




  </div>

</template>

<script>
import SingleUpload from '@/components/Upload/singleUpload';
import {uploadAttachmentFile,uploadArticleImagesByOss,createArticle,deleteArticle,updateArticle,selectArticle,findByPage} from '@/api/article';
import {createArticleAttachment} from '@/api/attachment';
import {getChannelTree} from "@/api/channel";
import Vue from 'vue';
import mavonEditor from 'mavon-editor';
import 'mavon-editor/dist/css/index.css';
Vue.use(mavonEditor);


export default {
  name: "index",
  components:{SingleUpload},
  data() {
    return {
      pagination: {//分页数据模型数
        currentPage: 1,//当前页码
        pageSize: 10,//每页显示的记录数
        total: 0,//总记录数
        queryParams: {}//查询条件
      },
      defaultProps: { //自定义树形节点属性
        id: 'id',
        parentId: 'parentId',
        label: 'name',
        children: 'children'
      },
      selectNodeID: 6,//选择栏目类型的ID 默认第2栏
      channelDateList: [], //咨询分类数据
      dataList: [],//当前页要展示的分页列表数据
      formData: {},//表单数据
      ArticleAttachment:{},//文件附件
      titleImg: null, //咨询首图路径
      articleAttachment:null,//附件
      dialogFormVisible: false,//增加表单是否可见
      dialogFormVisible4Edit: false,//修改表单是否可见
      dialogFormVisible4AddAttachment:false,//添加咨询附件的表单是否可见
      active: 0, //默认高亮第一个
      multipleSelection: [], //选中项数据的数组
      rule: {//表单的校验规则
        title: [{required: true, message: '请输入咨询的标题', trigger: 'blur'}],
        summary: [{required: true, message: '请输入咨询的简要', trigger: 'blur'}],
        author: [{required: true, message: '请输入咨询的作者', trigger: 'blur'}],
        content: [{required: true, message: '请输入内容', trigger: 'blur'}],
        sort: [{required: true, message: '请输入咨询的排序号', trigger: 'blur'}],
        status: [{required: true, message: '请输入咨询的状态', trigger: 'blur'}],
      },


    }

  },
  created() {
    this.getChannelTree()
    this.findArticleByPage()
  },
  methods: {

    //咨询附件上传前的处理的方法
    handleAttachmentBeforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 / 2
      if (!isLt2M) {
        this.$message.error('上传的文件大小不能超过 2MB!');
      }
      return isLt2M

    },

    //处理自定义的咨询附件上传的方法
    handleAttachmentHttpRequest(params) {
      let formData = new FormData();
      formData.append('uploadAttachmentFile', params.file);
      //图片名称
      formData.append('FileName', params.file.name);
      uploadAttachmentFile(formData).then(res=>{
        this.$notify({
          type: 'success',
          title: '附件成功上传!',
          message: '恭喜你，附件上传成功',
          offset: 300
        });
        //得到后端返回的附件URL，articleAttachment附件数据模型
        this.articleAttachment.name = res.data.name;
        this.articleAttachment.url = res.data.url;
      })
    },

    //上传咨询配图之前的处理方法
    beforeTitleImageUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M
    },

    //处理咨询配图上传
    handleHttpRequest(params) {
      let formData = new FormData();
      formData.append('uploadImage', params.file);
      formData.append('FileName', params.file.name);
      uploadArticleImagesByOss(formData).then(res=>{
        this.formData.titleImg = res.data
        this.titleImg = res.data
        this.$notify({
          type: 'success',
          title: '咨询配图成功上传!',
          message: '恭喜你，图片上传成功！',
          offset: 300
        });
      })

    },

    // 富文本编辑器，图片上传保存到阿里云的OSS存储中
    handleEditorImgAdd(pos, $file) {
      const formData = new FormData()
      formData.append('uploadImage', $file)
      uploadArticleImagesByOss(formData).then(res=>{
        const url = res.data
        //将此URL赋值给富文本编辑器
        this.$refs.md.$img2Url(pos, url);
      })
    },

    //处理树形节点点击
    handleNodeClick(data) {
      console.info(`【====检测到当前用户点击了咨询分类树====】`);
      //把咨询分类的ID赋值给selectNodeID
      this.selectNodeID = data.id
      this.findArticleByPage()
    },

    //弹出新增表单窗口的方法
    handleAddDialog() {
      console.info("【======系统正在弹出的添加咨询窗口=====】")
      //重置表单数据
      this.resetForm();
      //显示新增窗口
      this.dialogFormVisible = true;

      console.info("【系统成功弹出的添加咨询窗口！!!!】")
    },

    //处理添加的方法
    handleAdd(formName) {
      console.info("【系统正在进行增加咨询....】")
      this.formData.articleAttachmentParam = this.articleAttachment
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //新增咨询
          createArticle(this.formData).then(res=>{
              this.$message({
                showClose: true,
                message: '恭喜你，操作成功',
                type: 'success',
                onClose: () => {
                  this.handleCurrentChange(1)
                }
              });
           })

          //关闭新增窗口
          this.dialogFormVisible = false;

          //重置表单数据
          this.resetForm()

          //刷新列表数据
          this.handleCurrentChange(1)
          this.getChannelTree()

        }
      });
      console.info("【======系统增加咨询成功！====】")
    },

    //关闭新增表单窗口的方法
    handleAddFormClose() {
      //关闭新增表单对话框
      this.dialogFormVisible = false
      //设置表单数据模型为空
      this.resetForm();
    },

    //弹出编辑窗口的方法
    handleUpdateDialog() {
      if (this.multipleSelection.length === 1) {
        console.info("【====系统正在弹出的修改咨询窗口====】")
        //清空表单项
        this.resetForm();
        //弹出编辑窗口
        this.dialogFormVisible4Edit = true;

        //获取咨询栏目ID
        const articleId = this.multipleSelection[0].id
        //发送请求
        selectArticle(articleId).then(res=>{
          //赋值给表单数据模型
          this.formData = res.data
          this.titleImg = res.titleImg
        })
        console.info(`====【系统正在弹出的修改咨询窗口成功！！并成功获取了ID为：${articleId}的咨询详情=====`)
      } else {
        //弹出成功框，显示成功信息
        this.$message({
          showClose: true,
          message: '请选择一行数据修改',
          type: 'warning',
          onClose: () => {
            this.findArticleByPage()
          }
        })
      }


    },

    //处理修改的方法
    handleEdit(formName) {
      this.$refs[formName].validate((valid) => {
        console.info("【系统正在进行修改咨询....】")
        if (valid) { //校验成功
          updateArticle(this.formData).then(res=>{
            this.$message({
              showClose: true,
              message: '恭喜你，操作成功',
              type: 'success',
              onClose: () => {
                this.handleCurrentChange(1);
              }
              })

            this.dialogFormVisible4Edit = false
            this.resetForm()
            this.handleCurrentChange(1)
            console.info("【系统成功修改咨询....】")

          });
        }
      });
    },

    //关闭修改表单窗口的方法
    handleEditFormClose() {
      //关闭修改表单对话框
      this.dialogFormVisible4Edit = false
      //设置表单数据模型为空
      this.resetForm();
    },

    //弹出添加咨询附件窗口的方法
    handleAddArticleAttachmentDialog() {
      if (this.multipleSelection.length === 1) {
        console.info("【====系统正在弹出添加咨询附件窗口====】")
        //清空表单项
        this.resetForm();
        //弹出添加咨询附件窗口
        this.dialogFormVisible4AddAttachment = true;
        //获取咨询ID
        const articleId = this.multipleSelection[0].id
        //赋值给数据模型
        this.articleAttachment.articleId = articleId;
        console.info(`====【系统正在弹出的添加咨询窗口成功！！并准备为咨询ID为：${articleId}的添加咨询附件！=====`)
      } else {
        //弹出成功框，显示成功信息
        this.$message({
          showClose: true,
          message: '请选择一条咨询进行添加附件',
          type: 'warning',
          onClose: () => {
            this.findArticleByPage()
          }
        })
      }


    },

    //添加咨询附件的方法
    handleAddArticleAttachment(formName) {
      this.$refs[formName].validate((valid) => {
        console.info("【系统正在进行添加咨询附件....】")
        if (valid) { //校验成功
            //发送请求
            createArticleAttachment(this.articleAttachment).then(res=>{
              //弹出成功框，显示成功信息
              this.$message({
                showClose: true,
                message: '恭喜你，操作成功',
                type: 'success',
                onClose: () => {
                  this.handleCurrentChange(1);
                    }
                })
              });

            //关闭添加咨询附件的窗口。
            this.dialogFormVisible4AddAttachment = false
            this.handleCurrentChange(1)
            console.info("【系统成功添加咨询附件....】")
        }
      });
    },

    //关闭添加咨询附件窗口的方法
    handleAddAttachmentFormClose() {
      this.dialogFormVisible4AddAttachment = false
      this.resetForm();
    },

    //处理删除
    handleDelete() {
      if (this.multipleSelection.length === 1) {
        //获取字典ID
        const articleId = this.multipleSelection[0].id
        //发送请求给后端删除
        deleteArticle(articleId).then(res=>{
          //弹出成功提示框，显示成功信息
          this.$message({
            showClose: true,
            message: '恭喜你，操作成功',
            type: 'success',
            onClose: () => {
              this.handleCurrentChange(1)
            }
          })
        })

      } else {
        //弹出成功提示框，显示成功信息
        this.$message({
          showClose: true,
          message: '请选择一行数据删除',
          type: 'warning',
          onClose: () => {
            this.handleCurrentChange(1)
          }
        })
      }

    },

    //重置表单的方法
    resetForm() {
      this.formData = {}
      this.titleImg = ''
      this.articleAttachment={}
    },

    //处理表格勾选
    handleSelectionChange(val) {
      //获取用户勾选想赋值数据模型multipleSelection
      this.multipleSelection = val;
    },

    //查询全部咨询分类的方法
    getChannelTree() {
      getChannelTree().then(res=>{
        this.channelDateList = res.data;
      })

    },

    //处理字典类型被点击的方法
    handleTypeDateClick(index, channelId) {
      console.log("==========当前字典类型被点击了======" + channelId)
      //设置类型激活属性为当前项索引值
      this.active = index
      this.selectNodeID = channelId
      //调用findByPage方法
      this.findArticleByPage()
    },


    //处理分页查询字典数据的方法
    findArticleByPage() {
      this.pagination.queryParams.channelId = this.selectNodeID
      findByPage(this.pagination).then(res=>{
        this.dataList = res.data.rows;
        this.pagination.total = res.data.total;
      })
    },

    //改变每页显示的条数
    handleSizeChange(pageSize) {
      this.pagination.pageSize = pageSize
      this.findArticleByPage()
    },

    //切换页码
    handleCurrentChange(currentPage) {
      this.pagination.currentPage = currentPage;
      this.findArticleByPage()
    },


  }


}
</script>

<style scoped>
/*咨询配图相关样式*/
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
/*咨询配图相关样式*/


.type{
  list-style: none;
  margin: 0px;
  padding: 0px;
}
.type li{
  height: 40px;
  padding-left: 20px;
  line-height: 40px;
  box-sizing: border-box;
  cursor: pointer;
  font-size: 14px;
}
.type .active{
  background-color: #1AA094;
  color: #ffffff;
  border-radius: 10px;
}
</style>
